import Vue from "vue";
import VueRouter from "vue-router";
import routes from "@/router/routers";
//引入store
import store from "@/store/index";
Vue.use(VueRouter);
//配置路由

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
  //始终保持滚动条在顶部
  // eslint-disable-next-line no-unused-vars
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { y: 0 };
  },
});
// 解决重复点击相同路由报错问题(push)
//保存原型对象上的push
const VueRouterPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(to) {
  return VueRouterPush.call(this, to).catch((err) => err);
};
// 解决重复点击相同路由报错问题(Replace)
let originReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function (to, resole, reject) {
  if (resole && reject) {
    originReplace.call(this, to, resole, reject);
  } else {
    originReplace.call(
      this,
      to,
      () => {},
      () => {}
    );
  }
};

//全局守卫
router.beforeEach(async (to, from, next) => {
  //获取token
  let token = localStorage.getItem("token");
  let name = store.state.user.userInfo.name;
  //判断有没有token
  if (token) {
    //已经登录
    if (to.path == "/login" || to.path == "/register") {
      //拦截到首页
      next("/home");
    } else {
      if (name) {
        next();
      } else {
        try {
          await store.dispatch("user/getUserInfo");
          next();
        } catch (error) {
          //token失效
          await store.dispatch("user/outLogin");
          this.$message.success("token失效");
          next("/login");
        }
      }
    }
  } else {
    //没有登录
    //判断需不需要权限
    if (to.meta.isAuther == true) {
      //需要登录
      next("/login?redirect=" + to.path); //把想要去的地方传到地址栏上
    } else {
      next();
    }
  }
});
export default router;
